import { useState } from 'react';

import clsx from 'clsx';

type FilterDataItem = {
	value: string;
	label: string;
};
// 定义筛选数据的类型
type FilterData = {
	[key: string]: FilterDataItem[];
};

// 定义筛选状态的类型
type SelectedFilters = {
	[key: string]: string[];
};
interface FilterAreaProps {
	value?: any;
	filterListNames: Record<string, string>;
	filterData: FilterData;
	className?: string;
	showResult?: boolean;
	onChange?: (selectedFilters: SelectedFilters) => void;
}

const FilterAreaComponent = (props: FilterAreaProps) => {
	const { filterData, className, showResult, value, filterListNames } = props;
	// 状态管理
	const [selectedFilters, setSelectedFilters] = useState<SelectedFilters>(value);
	const [isShow, setIsShow] = useState(false);
	const getLabel = (value: string) => {
		let label = '';
		Object.entries(filterData).forEach(([_, items]) => {
			items.forEach(item => {
				if (item.value === value) {
					label = item.label!;
				}
			});
		});
		return label;
	};

	// useEffect(() => {
	// 	const selectedFiltersInit: SelectedFilters = {};
	// 	Object.entries(filterData).forEach(([category, items]) => {
	// 		selectedFiltersInit[category] = [items[0].value];
	// 	});
	// 	setSelectedFilters(selectedFiltersInit);
	// }, [filterData]);

	useEffect(() => {
		if (props?.onChange) {
			props.onChange(selectedFilters);
		}
	}, [selectedFilters]);
	/**
	 * 处理筛选项点击事件
	 * @param category - 筛选类别
	 * @param item - 选中的筛选项
	 *
	 * @example
	 * handleFilterClick('区域', '中国');
	 */
	const handleFilterClick = (category: string, item: string) => {
		let oldValue = selectedFilters[category];
		if (item == 'all') {
			oldValue = ['all'];
		} else if (oldValue.includes(item)) {
			oldValue = oldValue.filter(i => i != item);
		} else {
			oldValue = [...oldValue, item];
		}
		// 判断包含all 又包含别的则移出all
		if (oldValue.includes('all') && oldValue.length > 1) {
			oldValue = oldValue.filter(i => i != 'all');
		}
		setSelectedFilters({
			...selectedFilters,
			[category]: oldValue
		});
	};

	/**
	 * 渲染筛选行
	 * @param category - 筛选类别
	 * @param items - 筛选项列表
	 * @returns JSX.Element - 筛选行的 JSX 元素
	 *
	 * @example
	 * renderFilterRow('区域', ['全部', '中国', '欧盟']);
	 */
	const renderFilterRow = (category: string, items: FilterDataItem[]) => (
		<div className="flex items-center   w-full">
			<div className="h-[30px] w-10 text-sm color-[rgba(0,0,0,0.45)] font-medium mr-2 flex-shrink-0">
				{filterListNames?.[category] ?? category}
			</div>
			<div
				className="flex flex-wrap gap-1 flex-1
			mb-2"
			>
				{items.map(item => (
					<button
						key={item.value}
						onClick={() => handleFilterClick(category, item.value)}
						className={`
              px-2 py-1  rounded transition-all duration-200 whitespace-nowrap
              ${
								selectedFilters[category]?.includes?.(item.value)
									? 'bg-#F2F8F7 color-primary '
									: 'color-[rgba(0, 0, 0, 0.65)] bg-white hover:bg-#F2F8F7 '
							}
            `}
					>
						{item.label}
					</button>
				))}
			</div>
		</div>
	);
	const len = useMemo(() => {
		return isShow ? Object.entries(filterData).length : 1;
	}, [filterData, isShow]);
	return (
		<div className={clsx('w-full  mx-auto bg-white rounded-lg   relative', className)}>
			<div className="px-6 py-2">
				{Object.entries(filterData).map(([category, items], index) => {
					if (index < len) {
						return <div key={category}>{renderFilterRow(category, items)}</div>;
					}
					return null;
				})}
			</div>
			<div className="absolute top-2 right-4 cursor-pointer" onClick={() => setIsShow(!isShow)}>
				<ATooltip title={isShow ? '收起筛选' : '展开筛选'} placement="bottom">
					<SvgIcon
						localIcon={isShow ? 'collapse-icon' : 'expand-icon'}
						className="color-primary text-5"
					/>
				</ATooltip>
			</div>

			{/* 显示当前选择的筛选条件 */}
			{showResult && (
				<div className="px-6 py-4 bg-gray-50 border-t border-gray-200">
					<div className="text-sm text-gray-600">
						<span className="font-medium">当前筛选：</span>
						{Object.entries(selectedFilters).map(([key, value], index) => (
							<span key={key} className="ml-2">
								{index > 0 && ' | '}
								<span className="font-medium color-[rgba(0,0,0,0.45)]">{key}:</span>
								<span className="color-primary ml-1">{getLabel(value)}</span>
							</span>
						))}
					</div>
				</div>
			)}
		</div>
	);
};

export default FilterAreaComponent;
